<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      table {
        width: 500px;
        margin: 100px auto;
        border-collapse: collapse;
        text-align: center;
      }

      td,
      th {
        border: 1px solid #333;
      }

      thead tr {
        height: 40px;
        background-color: #ccc;
      }
    </style>
  </head>

  <body>
    <table cellspacing="0">
      <thead>
        <tr>
          <th>姓名</th>
          <th>科目</th>
          <th>成绩</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script>
      // 学生数据
      var datas = [
        {
          name: "张三",
          subject: "JavaScript",
          score: 100,
        },
        {
          name: "李四",
          subject: "JavaScript",
          score: 98,
        },
        {
          name: "王五",
          subject: "JavaScript",
          score: 99,
        },
        {
          name: "赵六",
          subject: "JavaScript",
          score: 88,
        },
      ];
      // 根据提供的学生数据的数组长度在tbody中创建行
      var tbody = document.querySelector("tbody");
      for (var i = 0; i < datas.length; i++) {
        //创建行
        var tr = document.createElement("tr");
        //插入行
        tbody.appendChild(tr);
        //遍历学生对象,为行添加元素
        for (var k in datas[i]) {
          //创建列
          var td = document.createElement("td");
          //添加内容入列
          td.innerHTML = datas[i][k];
          //列插入到行
          tr.appendChild(td);
        }
        //创建列，用于放删除按钮
        var td = document.createElement("td");
        td.innerHTML = '<a href="javascript:;">删除 </a>';
        tr.appendChild(td);
      }
      //为所有删除按钮添加删除事件
      var delBtns = document.querySelectorAll("a");
      for (var i = 0; i < delBtns.length; i++) {
        delBtns[i].onclick = function () {
          //删除对于的行
          tbody.removeChild(this.parentNode.parentNode);
        };
      }
    </script>
  </body>
</html>
